package com.ec50n9.server.module.common

import com.ec50n9.server.common.mayBeAlreadyExist
import com.ec50n9.server.common.mayBeNotFound
import org.springframework.data.repository.CrudRepository

abstract class BaseService<T : Render<*>, ID : Any>(val name: String, private val repository: CrudRepository<T, ID>) {

    open fun findOne(id: ID): T = mayBeNotFound(name) {
        repository.findById(id).orElseThrow()
    }

    open fun findAll(): Iterable<T> = repository.findAll()

    open fun newOne(t: T) = mayBeAlreadyExist(name) {
        repository.save(t)
    }

    open fun update(t: T) = repository.save(t)

    open fun delete(t: T) = repository.delete(t)
}